import { HttpError, toSuccess, useEntityManager, useRedis } from "@sker/core";
import { KsLiveRoom, KsRedPacket } from "@sker/entities";
import { useData } from "@sker/runtime";
import axios from "axios";
import dayjs from "dayjs";
import { DependencyContainer } from "tsyringe";
import { z } from "zod";
// 目前在用
async function getRealLink(link: string) {
    try {
        const response = await axios.get(link)
        const [path, query] = response.request.path.split(`?`)
        const res = path.match(/fw\/live\/(.*)/)
        if (res && res.length > 0) {
            const [, ksid] = res;
            const params: any = {}
            query.split('&').map(key => {
                const [name, value] = key.split('=');
                params[name] = value;
            });
            return { ...params, ksid };
        }
    } catch (e) {
        return {}
    }
}
export default async (injector: DependencyContainer) => {
    const input = z.object({
        room_id: z.optional(z.number()),
        online: z.optional(z.number()),
        openTime: z.string(),
        readPacketCount: z.optional(z.number()),
        rank: z.optional(z.string()),
        redPackets: z.array(z.any()),
        category: z.optional(z.string()),
    });
    const body = input.parse(useData());
    // room
    let {  redPackets, online, openTime, rank, category, room_id } = body;
    if (!room_id) {
        return toSuccess(`失败`)
    }

    /**
     * 出入数据库
     */
    await useEntityManager(async m => {
        // 账户
        let room = await m.findOne(KsLiveRoom, { where: { id: body.room_id } })
        if(!room) throw new HttpError(`参数错误`)
        // 房间
        const maxCount = redPackets.map(a => a?.count || 0).reduce((a, b) => a > b ? a : b, 0)
        await m.update(KsLiveRoom, room.id, { max_count: maxCount, open_time: openTime, online, rank, category });
        const toSaveRedPackets = redPackets.map(red => {
            return m.create(KsRedPacket, {
                type: red.type,
                count: red.count,
                total: red.total,
                open_time: red.open_time || openTime,
                password: red.password,
                text: red.text,
                room_id: room_id
            })
        });
        // 口令包
        const reds = await m.save(KsRedPacket, toSaveRedPackets)
        /**
         * 存入缓存
         */
        await useRedis(7, async r => {
            async function setWithExpiration(hashName: string, fieldValue: string, expirationTime: number) {
                await r.set(hashName, fieldValue);
                await r.expire(hashName, expirationTime);
            }
            const expireTime = Math.floor((dayjs(openTime, 'YYYY-MM-DD HH:mm:ss').subtract(1.5, 'minute').toDate().getTime() - dayjs().toDate().getTime()) / 1000)
            await setWithExpiration(`rooms.${room.user_id}`, JSON.stringify({
                ...room,
                reds
            }), expireTime)
        });
        return room_id;
    });
    // 加入到redis缓存
    return toSuccess({})
}


/**
 * 抓到红包后 
 * 将红包信息 加入到缓存
 * 红包类型
 * 
 * 红包信息
 * 
 * hset(redpackets, red_id，过期时间)
 * 
 * 红包池：
 * key: 红包类型.owner
 * vlaue: [] sort set
 * zadd(红包类型.owner, { red_id: count })
 * 
 * 红包派发池
 * 
 * 
 * 红包中币池
 * 
 * key: room_id + owner
 * value:  { link, name, user_id, room_id, money_v }
 * expir: open_time
 */